package org.fhm.zdte.client.provider;

import org.fhm.substrate.annotation.Setup;
import org.fhm.zdte.client.api.ClientApi;
import org.fhm.zdte.client.exception.ClientException;
import org.fhm.zdte.common.ability.IGetIdentification;
import org.fhm.zdte.common.annotation.InternalProvider;
import org.fhm.zdte.common.annotation.MapperParameter;
import org.fhm.zdte.common.annotation.RequestMapping;
import org.fhm.zdte.common.pojo.Result;
import org.fhm.zdte.common.pojo.Servlet;

import java.util.Objects;


/**
 * Common local {@link Servlet} provider.
 *
 * @author tanbo
 * @since 2024/1/12
 */
@InternalProvider
@RequestMapping("/common")
public class CommonInternalProvider {

    @Setup
    private IGetIdentification iGetIdentification;

    @Setup
    private ClientApi api;

    /**
     * Obtain myself identification.
     *
     * @return The response result.
     */
    @RequestMapping("/identification")
    private Result<String> getIdentification() {
        String identification = iGetIdentification.getIdentification();
        if (Objects.isNull(identification) || identification.isEmpty())
            Result.getFailResult("The client side is not online, and the server side is not assigned identification temporarily");
        return Result.getSuccessResult(identification);
    }

    /**
     * The client side goes-live.
     *
     * @return The response result.
     */
    @RequestMapping("/goLive")
    private Result<Void> goLive() {
        try {
            api.clientOnline();
            return Result.getSuccessMessage("go live successfully");
        } catch (ClientException e) {
            return Result.getFailMessage(e.getMessage());
        }
    }

    /**
     * Establish connection.
     *
     * @param target The identification of target end side.
     * @return The response result.
     */
    @RequestMapping("/connect")
    private Result<Void> establishConnection(@MapperParameter("target") String target) {
        try {
            return api.connect(target);
        } catch (ClientException e) {
            return Result.getFailMessage(e.getMessage());
        }
    }


    /**
     * Establish connection with a secret key.
     *
     * @param target    The identification of target end side.
     * @param secretKey The secret key of target client side.
     * @return The response result.
     */
    @RequestMapping("/connect/secretKey")
    private Result<Void> establishConnectionWithSecretKey(@MapperParameter("target") String target, @MapperParameter("secretKey") String secretKey) {
        try {
            return api.connect(target, secretKey, true);
        } catch (ClientException e) {
            return Result.getFailMessage(e.getMessage());
        }
    }


}
